package com.mars.miaosha.controller;

import com.mars.miaosha.domain.MiaoshaOrder;
import com.mars.miaosha.domain.MiaoshaUser;
import com.mars.miaosha.domain.OrderInfo;
import com.mars.miaosha.result.CodeMsg;
import com.mars.miaosha.service.GoodsService;
import com.mars.miaosha.service.MiaoshaService;
import com.mars.miaosha.service.OrderServive;
import com.mars.miaosha.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 秒杀操作
 * @author MARS
 * @date 2018/5/11
 */

@Controller
@RequestMapping("/miaosha")
@Slf4j
public class MiaoshaController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderServive orderServive;
    @Autowired
    private MiaoshaService miaoshaService;

    @RequestMapping("/do_miaosha")
    public String list(Model model, MiaoshaUser user, @RequestParam("goodsId") long goodsId){
        model.addAttribute("user",user);
        // 检查用户是否登录
        if (user == null) {
            return "login";
        }

        // 判断库存
        GoodsVo goodsVo = goodsService.getGoodsByGoodsId(goodsId);
        // 获取库存数量
        int stock = goodsVo.getGoodsStock();
        if (stock <= 0 ) {
            model.addAttribute("errmsg", CodeMsg.MIAO_SHA_OVER.getMsg());
            return "miaosha_fail";
        }

        // 查看是否已经秒杀到
        MiaoshaOrder miaoshaOrder = orderServive.getMiaoshaOrderByUserIdGoodsId(user.getId(),goodsId);
        if (miaoshaOrder != null) {
            model.addAttribute("errmsg",CodeMsg.REPEATE_MIAOSHA.getMsg());
            return "miaosha_fail";
        }

        // 减少库存，下订单，写入秒杀订单(需要在一个事务里去完成的操作)
        OrderInfo orderInfo = miaoshaService.miaosha(user,goodsVo);
        model.addAttribute("orderInfo",orderInfo);
        model.addAttribute("goods",goodsVo);
        return "order_detail";
    }
}
